package com.powernode.listen;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.powernode.constant.OrderStatusConstant;
import com.powernode.constant.QueueConstant;
import com.powernode.domain.Order;
import com.powernode.dto.EsChange;
import com.powernode.dto.OverTimerOrder;
import com.powernode.dto.SkuChang;
import com.powernode.feign.OrderPayFeign;
import com.powernode.feign.OrderProdFeign;
import com.powernode.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.dc.pr.PRError;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Component //交给spring容器管理
public class DeadMsgHandleListener {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderPayFeign orderPayFeign;

    @Autowired
    private OrderProdFeign orderProdFeign;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 监听死信队列
     * 获取到订单号 查询数据库订单的状态
     * 订单已支付：  直接签收消息即可
     * 订单未支付：
     * 此时再根据订单号去支付宝/微信查询支付扣款状态
     * 扣款成功：
     * 修改数据库的订单状态为已支付 并签收消息
     * 扣款失败：
     * 回退库存  修改订单的状态为超时未支付  并签收消息
     *
     * @param message
     * @param channel
     */
    @RabbitListener(queues = QueueConstant.ORDER_DEAD_QUEUE)
    public void overTimeOrder(Message message, Channel channel) throws IOException {
        String msg = new String(message.getBody());
        OverTimerOrder orderDto = JSON.parseObject(msg, OverTimerOrder.class);
        String orderNo = orderDto.getOrderNo();
        //根据订单号查询订单的状态
        Order one = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, orderNo));
        if (ObjectUtil.isNotEmpty(one)) {
            if (one.getStatus() == OrderStatusConstant.WAIT_PAY) {
                //根据订单号查询支付宝或者微信 该笔订单的扣款状况

                /*此时处于代付款状态
                 * 此时主动去调用支付宝那边的支付情况
                 * 如果返回的是已经付款则修改订单状态   代发货
                 * 如果返回为未支付 则关闭订单 回退es和数据库库存
                 * */

                if (orderPayFeign.getOrderStatusFeign(orderNo)) {
                    //已经支付直接修改订单
                    changeOrderSuccess(orderNo);
                } else {
                    //关闭订单 并且回退库存
                    changeOrderFail(orderDto);
                }
            }
            //手动签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        }

    }

    private void changeOrderFail(OverTimerOrder orderDto) {

        orderService.update(new UpdateWrapper<Order>()
                .eq("order_number", orderDto.getOrderNo())
                .set("status", OrderStatusConstant.ORDER_FAIL)
                .set("close_type", 1)
                .set("create_time", new Date())
                .set("update_time", new Date()));
        //回退es库存 和 回退sku库存
        List<EsChange> esChangeList = orderDto.getChangeDto().getEsChangeList();
        List<SkuChang> skuChangList = orderDto.getChangeDto().getSkuChangList();
        esChangeList.stream().forEach(esChange -> esChange.setNumber(esChange.getNumber() * -1));
        skuChangList.stream().forEach(skuChang -> skuChang.setNumber(skuChang.getNumber() * -1));
        orderProdFeign.changeDBOrder(orderDto.getChangeDto());
        rabbitTemplate.convertAndSend(QueueConstant.ES_CHANGE_QUEUE, JSON.toJSONString(esChangeList));
    }

    private void changeOrderSuccess(String orderNo) {
        orderService.update(new UpdateWrapper<Order>()
                .eq("order_number", orderNo)
                .set("status", OrderStatusConstant.WAIT_FAHUO)
                .set("create_time", new Date())
                .set("update_time", new Date()));
    }
}
